<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 添加搜索区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="用户名">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input
              v-model="queryParams.realName"
              placeholder="请输入真实姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input
              v-model="queryParams.phone"
              placeholder="请输入手机号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="角色">
            <el-select 
              v-model="queryParams.roleType" 
              placeholder="请选择角色"
              clearable
            >
              <el-option 
                v-for="role in roleOptions" 
                :key="role.id"
                :label="role.roleName"
                :value="role.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="queryParams.status" 
              placeholder="请选择状态"
              clearable
            >
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 原有的表头操作区 -->
      <div slot="header" class="clearfix">
        <span>用户管理</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text"
          @click="handleAdd"
        >
          新增用户
        </el-button>
      </div>
      
      <el-table 
        :data="tableData" 
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column label="角色" width="100">
          <template slot-scope="{row}">
            <el-tag :type="getRoleType(row.roleType)">
              {{ getRoleText(row.roleType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.status ? 'success' : 'info'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="{row}">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              type="text" 
              @click="handleToggleStatus(row)"
            >
              {{ row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="text" 
              style="color: #F56C6C"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!userForm.id">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="roleType">
          <el-select v-model="userForm.roleType" placeholder="请选择角色">
            <el-option 
              v-for="role in roleOptions" 
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'UserManagement',
  data() {
    // 自定义邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (value && !emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }
    // 自定义手机号验证规则
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      if (value && !phoneRegex.test(value)) {
        callback(new Error('请输入正确的手机号格式'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      tableData: [],
      roleOptions: [],
      
      dialogVisible: false,
      dialogTitle: '新增用户',
      userForm: {
        id: null,
        username: '',
        password: '',
        realName: '',
        email: '',
        phone: '',
        roleType: null,
        status: true,
        isDeleted: false
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        roleType: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      // 添加查询参数对象
      queryParams: {
        username: '',
        realName: '',
        phone: '',
        roleType: null,
        status: null
      }
    }
  },
  created() {
    this.fetchData()
    this.fetchRoles()
  },
  methods: {
    // 获取用户列表
    async fetchData() {
      this.loading = true
      try {
        // 构建查询参数
        const params = {}
        for (const key in this.queryParams) {
          if (this.queryParams[key] != null && this.queryParams[key] !== '') {
            params[key] = this.queryParams[key]
          }
        }

        const res = await request({
          url: '/api/admin/users',
          method: 'get',
          params: params // 添加查询参数
        })
        if (res.code === 200) {
          this.tableData = res.data
        } else {
          this.$message.error(res.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },
    // 获取角色列表
    async fetchRoles() {
      try {
        const res = await request({
          url: '/api/admin/roles',
          method: 'get'
        })
        if (res.code === 200) {
          this.roleOptions = res.data
        } else {
          this.$message.error(res.message || '获取角色列表失败')
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
        this.$message.error('获取角色列表失败')
      }
    },
    // 格式化角色类型
    getRoleType(roleType) {
      const role = this.roleOptions.find(r => r.id === roleType)
      if (role) {
        switch (role.roleCode) {
          case 'ADMIN':
            return 'danger'
          case 'MAINTAINER':
            return 'warning'
          case 'USER':
            return 'info'
          default:
            return 'info'
        }
      }
      return 'info'
    },
    // 格式化角色文本
    getRoleText(roleType) {
      const role = this.roleOptions.find(r => r.id === roleType)
      return role ? role.roleName : '未知'
    },
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString()
    },
    // 处理添加用户
    handleAdd() {
      console.log('点击新增用户按钮')
      this.dialogTitle = '新增用户'
      this.resetForm()
      this.dialogVisible = true
      console.log('dialogVisible:', this.dialogVisible)
    },
    // 处理编辑用户
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.userForm = {
        id: row.id,
        username: row.username,
        realName: row.realName,
        email: row.email,
        phone: row.phone,
        roleType: row.roleType,
        status: row.status,
        isDeleted: false
      }
      this.dialogVisible = true
    },
    // 处理切换用户状态
    async handleToggleStatus(row) {
      try {
        await this.$confirm(
          `确认${row.status ? '禁用' : '启用'}该用户吗？`, 
          '提示', 
          { type: 'warning' }
        )
        
        // 构造更新数据，保持其他字段不变
        const submitData = {
          id: row.id,
          username: row.username,
          realName: row.realName,
          email: row.email,
          phone: row.phone,
          roleType: row.roleType,
          status: !row.status,  // 切换状态
          isDeleted: false
        }

        const res = await request({
          url: '/api/admin/users/update',
          method: 'put',
          data: submitData
        })
        
        if (res.code === 200) {
          this.$message.success(`${row.status ? '禁用' : '启用'}成功`)
          this.fetchData()
        } else {
          this.$message.error(res.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
      }
    },
    // 处理删除用户
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该用户吗？', '提示', {
          type: 'warning'
        })
        const res = await request({
          url: `/api/admin/users/${row.id}`,
          method: 'delete'
        })
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.fetchData()
        } else {
          this.$message.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
      }
    },
    // 重置表单
    resetForm() {
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields()
      }
      this.userForm = {
        id: null,
        username: '',
        password: '',
        realName: '',
        email: '',
        phone: '',
        roleType: null,
        status: true,
        isDeleted: false
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            // 构造提交的数据
            const submitData = {
              username: this.userForm.username,
              realName: this.userForm.realName,
              email: this.userForm.email,
              phone: this.userForm.phone,
              roleType: this.userForm.roleType,
              status: this.userForm.status,
              isDeleted: false
            }

            // 如果是新增用户，需要包含密码字段
            if (!this.userForm.id) {
              submitData.password = this.userForm.password
            }

            // 如果是编辑模式，需要包含id
            if (this.userForm.id) {
              submitData.id = this.userForm.id
            }

            console.log('最终提交的数据:', submitData)

            // 根据是否有id判断使用不同的接口
            const res = await request({
              url: this.userForm.id ? '/api/admin/users/update' : '/api/admin/users',
              method: 'put',
              data: submitData
            })
            
            if (res.code === 200) {
              this.$message.success(this.userForm.id ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.message || (this.userForm.id ? '更新失败' : '添加失败'))
            }
          } catch (error) {
            console.error(this.userForm.id ? '更新用户失败:' : '添加用户失败:', error)
            this.$message.error((this.userForm.id ? '更新' : '添加') + '失败: ' + (error.message || '未知错误'))
          }
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },
    // 处理查询
    handleQuery() {
      this.fetchData()
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        username: '',
        realName: '',
        phone: '',
        roleType: null,
        status: null
      }
      this.fetchData()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
}

.el-form-item {
  margin-bottom: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-dialog {
  margin-top: 8vh !important;
}
</style> 